package rulesControl;

import java.util.Map;
import java.util.TreeMap;

import gameBasicElements.PlayerColor;

/**
 * @author Igor Adamski
 *
 */
public class StandardByoYomi implements ByoYomi {
	private int periodLength;
	private Map<PlayerColor, Integer> periodsLeft = new TreeMap<PlayerColor, Integer>();
	private Map<PlayerColor, Integer> timeLeft = new TreeMap<PlayerColor, Integer>();
	private int initTime;
	public StandardByoYomi(int initTime, int periodLength, int periodsInitAmount) {
		timeLeft.put(PlayerColor.BLACK, initTime);
		timeLeft.put(PlayerColor.WHITE, initTime);
		this.periodLength = periodLength;
		periodsLeft.put(PlayerColor.BLACK, periodsInitAmount);
		periodsLeft.put(PlayerColor.WHITE, periodsInitAmount);
		this.initTime = initTime;
	}
	
	@Override
	public int getTimeLeft(PlayerColor color) {
		return timeLeft.get(color) + periodLength * periodsLeft.get(color);
	}

	@Override
	public void update(PlayerColor color, int timeUsed) {
		timeUsed = Math.min(timeUsed, getTimeLeft(color));
		int used = Math.min(timeUsed, timeLeft.get(color));
		timeLeft.put(color, timeLeft.get(color) - used);
		timeUsed -= used;
		if(timeUsed > 0) {
			periodsLeft.put(color, periodsLeft.get(color) - timeUsed / periodLength);
		}
	}

	@Override
	public int getInitTime() {
		return initTime;
	}

}
